package com.distributed.tcp.manager;

import com.distributed.tcp.enums.TcpPortEnum;
import com.distributed.tcp.model.ClientChannelAttrs;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.UUID;

import static com.distributed.tcp.enums.TcpPortEnum.DEVICE_A;
import static com.distributed.tcp.enums.TcpPortEnum.DEVICE_B;

@Slf4j
@Component("messageExecute")
public class MessageExecuteHandler implements MessageHandler {

    /**
     * 通过端口号区分调用的设备信息
     * @param channel
     * @param port
     * @param message
     * @param connectionManager
     */
    @Override
    public void handleMessage(Channel channel,int port, String message,
                             DeviceConnectionManager connectionManager) {
        try {
            TcpPortEnum watchPortEnum = TcpPortEnum.getByPort(port);
            if(watchPortEnum == null){
                return;
            }
            // 设备信息
            switch (watchPortEnum) {
                case DEVICE_A:
                    handleDeviceAMessage(DEVICE_A.getName(),channel,message,connectionManager);
                    break;
                case DEVICE_B:
                    handleDeviceBMessage(DEVICE_B.getName(),channel,message,connectionManager);
                    break;
            }
        } catch (Exception e) {
            log.error("处理消息失败", e);
            sendMessage(channel, "处理消息失败: " + e.getMessage());
        }
    }

    private void handleDeviceBMessage(String deviceName ,Channel channel,String message,DeviceConnectionManager connectionManager) {
    }

    /**
     *  设备A处理设备信息
     *
     *  注意：拿到TCP信息后，建议将原始数据直接丢到消息队列中，让对应的处理设备信息，处理内容
     *
     * @param deviceName
     * @param channel
     * @param message
     * @param connectionManager
     */
    private void handleDeviceAMessage(String deviceName ,Channel channel,String message,DeviceConnectionManager connectionManager) {
        // TODO 解析自己的TCP协议 解析数据，拿到设备号，注册连接，根据心跳续约连接。
        log.info("{} 设备的原始信息 {} ",deviceName,message);
        String deviceCode = channel.attr(ClientChannelAttrs.DEVICE_CODE).get();
        if(StringUtils.isBlank(deviceCode)){
            //1.随机生成设备号
            deviceCode = UUID.randomUUID().toString();
        }
        //设备号设置到连接中
        channel.attr(ClientChannelAttrs.DEVICE_CODE).set(deviceCode);
        //2.注册新连接
        connectionManager.registerConnection(channel,deviceCode);
        //3.device不为空，续约连接
        connectionManager.renewalDevice(deviceCode);
        log.info(" 处理设备 {} 的信息 {} ",channel.attr(ClientChannelAttrs.DEVICE_CODE).get(),message);
        // 根据业务回复响应
        String response = "其他协议号#";
        log.info("平台回复响应: {}" , response);
        sendMessage(channel, response);
    }

    @Override
    public boolean sendMessage(Channel channel, String message) {
        if (channel == null || !channel.isActive()) {
            log.warn("通道不活跃，无法发送消息");
            return false;
        }
        try {
            channel.writeAndFlush(message + "\r\n");
            return true;
        } catch (Exception e) {
            log.error("发送消息失败", e);
            return false;
        }
    }
}
